import { CONST_SingleResourceAction, type IReqSingleResource, type ISingleResourceOptions, type SingleResourceActionType, type SingleResourceData } from "@packages/shared"
import const_API, { type OnBusinessError, type OnError, type OnSuccess } from "./http.hook"

export const useRest = (resource: string, onSuccess?: OnSuccess, onBusinessError?: OnBusinessError, onError?: OnError) => {
    const setSingleResourceConfig = (action: SingleResourceActionType, options: ISingleResourceOptions): IReqSingleResource => {
        return {
            resource,
            action,
            options
        }
    }

    const list = (options: ISingleResourceOptions) => const_API.singleResource(
        {
            param: setSingleResourceConfig(CONST_SingleResourceAction.LIST, options),
            onSuccess,
            onBusinessError,
            onError
        }
    )

    const create = <T extends SingleResourceData>(data: T) => const_API.singleResource(
        {
            param: setSingleResourceConfig(CONST_SingleResourceAction.CREATE, { data }),
            onSuccess,
            onBusinessError,
            onError
        }
    )

    const update = <T extends SingleResourceData>(data: T) => const_API.singleResource(
        {
            param: setSingleResourceConfig(CONST_SingleResourceAction.UPDATE, { data }),
            onSuccess,
            onBusinessError,
            onError
        }
    )

    const remove = (_id: string) => const_API.singleResource(
        {
            param: setSingleResourceConfig(CONST_SingleResourceAction.DELETE, { data: { _id } }),
            onSuccess,
            onBusinessError,
            onError
        }
    )

    return {
        list,
        create,
        update,
        remove,
    }

}